package custom.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 本案例演示定制队列，交换机，绑定的配置（模仿Rabbitmq官网的topic手册的例子）
 *
 * 先声明交换机以及交换机与队列的绑定情况（依据路由key的模式），支持*与#2个特殊符号
 *
 * 发送消息时依据routing key，把消息从交换机分发到符合绑定的所有队列中去
 */
@Configuration
public class CustomBindingConfiguration {

    public static final String EXCHANGE_TOPIC_NAME = "mytopicA";
    public static final String QUEUE1 = "custom1";
    public static final String QUEUE2 = "custom2";

    @Bean
    public Queue myQueueA() {
        //第三个参数exclusive=true时表示只有声明队列的连接可以使用此队列
        return new Queue(CustomBindingConfiguration.QUEUE1,false,true,true);
    }

    //推荐用这种builder的写法来创建对象（QueueBuilder，BindingBuilder，MessageBuilder）
    @Bean
    public Queue myQueueB() {
        return QueueBuilder.nonDurable(CustomBindingConfiguration.QUEUE1).autoDelete().exclusive().build();
    }

    @Bean
    public TopicExchange topicExchange(){
        //第二个参数表示持久化（false是非持久化），第三个参数表示是否自动删除
        TopicExchange topicExchange = new TopicExchange(EXCHANGE_TOPIC_NAME,false,true);
        return topicExchange;
    }

    /**
     *  *(星号）表示一个单词，#（井号）表示0到多个单词
     * @return
     */
    @Bean
    public Binding bindingA(){
        Binding binding = new Binding(CustomBindingConfiguration.QUEUE1, Binding.DestinationType.QUEUE,EXCHANGE_TOPIC_NAME,"*.orange.*",null);
        return binding;
    }

    @Bean
    public Binding bindingB(){
        return BindingBuilder.bind(myQueueB()).to(topicExchange()).with("*.*.rabbit");
    }

    @Bean
    public Binding bindingC(){
        return BindingBuilder.bind(myQueueB()).to(topicExchange()).with("lazy.*.#");
    }


    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

}
